<template>
    <div>
        <van-nav-bar id="reset" title="家庭服务套餐" left-arrow @click-left="backHandle" fixed z-index="100" />
        <div class="pageCon">
            <div class="topBox">
                <div class="topImg">
                    <span>家庭服务套餐</span>
                    <span>亲情就诊、解锁科普</span>
                    <span>免排队优先问诊</span>
                </div>
            </div>
            <div class="itemCon">

                <div class="itemTop" v-if="!isVip && num1 == 0">
                    亲情服务
                </div>
                <div class="itemTop itemTop2 " v-else>
                    <div>
                        亲情服务
                        <span>当前剩余 {{ num1 }}次</span>
                    </div>
                    <div>
                        <span @click="handle(1, 'add')">提交申请</span>
                        <span></span>
                        <span @click="handle(1, 'detail')">使用详情</span>
                        <template v-if="num1 == 0">
                            <span></span>
                            <span @click="submitHandle(1, 100)">购买次数</span>
                        </template>

                    </div>
                </div>
                <div class="itemMain">
                    <div>
                        <img src="../../assets/img/qinqing.png" alt="">
                    </div>
                    <div>关于情亲就诊的文案，内容如下关于情亲就诊的文案，内容 如下关于情亲就诊的文案，内容如下关于情亲就诊的文案， 内容如下关于情亲就</div>
                </div>
            </div>

            <div class="itemCon">

                <div class="itemTop" v-if="!isVip && num0 == 0">

                    加号服务
                </div>
                <div class="itemTop itemTop2 " v-else>
                    <div>
                        加号服务
                        <span>当前剩余 {{ num0 }}次</span>
                    </div>
                    <div>
                        <span @click="handle(0, 'add')">提交申请</span>
                        <span></span>
                        <span @click="handle(0, 'detail')">使用详情</span>
                        <template v-if="num0 == 0">
                            <span></span>
                            <span @click="submitHandle(0, 100)" v-if="num0 == 0">购买次数</span>
                        </template>

                    </div>
                </div>
                <div class="itemMain">
                    <div>
                        <img src="../../assets/img/jiahao.png" alt="">
                    </div>
                    <div>关于情亲就诊的文案，内容如下关于情亲就诊的文案，内容 如下关于情亲就诊的文案，内容如下关于情亲就诊的文案， 内容如下关于情亲就</div>
                </div>
            </div>
            <div class="itemCon">
                <div class="itemTop" v-if="!isVip">
                    解锁全部专家知识分享
                </div>
                <div class="itemTop itemTop2 " v-else>
                    <div>
                        解锁全部专家知识分享
                    </div>
                    <div>
                        有效期至{{ user.vipTime }}
                    </div>
                </div>
                <div class="itemMain">
                    <div>
                        <img src="../../assets/img/jiesuo.png" alt="">
                    </div>
                    <div>关于情亲就诊的文案，内容如下关于情亲就诊的文案，内容 如下关于情亲就诊的文案，内容如下关于情亲就诊的文案， 内容如下关于情亲就</div>
                </div>
            </div>

            <div class="btn" @click="submitHandle(2, 365)">
                <template v-if="!isVip">
                    立即开通 <span>限时优惠</span> 365/年
                </template>
                <template v-else>
                    立即续费家庭套餐 365/年
                </template>
            </div>

        </div>


        <van-popup v-model="showPop" round>
            <div class="diaBox">
                <div>{{ orderType == 0 ? '加号' : '亲情就诊' }}申请</div>
                <div class="infoBox">
                    <div class="infoLine">
                        就诊人
                        <span>{{ user.userName }}</span>
                    </div>
                    <template v-if="orderType == 1">
                        <div class="infoLine">
                            就诊医生
                            <span>{{ form.doctorName }}</span>
                        </div>
                    </template>
                    <template v-else>
                        <div class="infoLine">
                            选择医生
                            <span @click="showListHandle(1)">{{ form.doctorName || '请选择' }}<van-icon
                                    name="arrow" /></span>
                        </div>
                        <!-- <div class="infoLine">
                            就诊时间
                            <span @click="showTime = true">{{ form.time || '请选择' }}<van-icon name="arrow" /></span>
                        </div> -->
                    </template>
                    <div class="infoLine" v-if="!ifMyNum">
                        审核人
                        <span @click="showListHandle(2)">{{ form.familyUserName || '请选择' }}<van-icon
                                name="arrow" /></span>
                    </div>

                    <div class="infoLine infoLine1" v-if="orderType == 1">
                        请上传您的病例等相关图片
                        <div class="imgBox">
                            <div>
                                <van-uploader v-model="fileList" :before-delete="beforeDelete" :after-read="afterRead"
                                    multiple :max-count="9" />
                            </div>
                        </div>

                    </div>


                </div>
                <div class="diaBtnBox">
                    <div @click="closeHandle">取消</div>
                    <div @click="addOrderHandle(orderType)">提交</div>
                </div>
            </div>
        </van-popup>

        <van-action-sheet v-model="showlist" :title="'选择您的' + (listFlag == 1 ? '医生' : '审核人')">
            <div class="doctorMain">
                <div v-for="( item, index ) in  selectList " :key="index">
                    <span>{{ item.name }}</span>
                    <div>
                        <span @click="selectHandle(1, item)" v-if="listFlag == 1">查看详情</span>
                        <span @click="selectHandle(2, item)">选择</span>
                    </div>
                </div>
            </div>
        </van-action-sheet>
        <van-action-sheet v-model="showTime">
            <van-datetime-picker @confirm="timeConfirm" @cancel="showTime = false" v-model="form.time" type="datetime"
                title="选择年月日" :min-date="minDate" />
        </van-action-sheet>
    </div>


</template>

<script>


import { userAddOrder, addUserOrder, listFamilyNum, payTest } from '../../network/family'
import { listDoctors } from '../../network/doctor'



export default {
    name: 'HomeR',
    data() {
        return {
            isLoading: false,
            isVip: localStorage.isVip == 1,
            myDoctorId: localStorage.myDoctorId,
            helperId: 1,
            payType: 0,  // 0消耗次数 1直接支付


            num0: 0,  // 加号服务次数
            num1: 0,  // 亲情服务次数

            showPop: false,
            showlist: false,
            showTime: false,

            orderType: 1,//  1 亲情就诊  0 加号


            form: {
                doctorName: '', //选择的医生
                doctorId: '',
                time: '',
                familyUserId: '',//审核人id
                familyUserName: '',//审核人id
            },
            doctorList: [],//医生列表
            familyList: [],//家庭成员（有次数） 列表

            minDate: new Date(),

            listFlag: 1,// 1 选择医生  2 选择审核人

            selectList: [],

            user: JSON.parse(localStorage.user),

            userId: localStorage.userId,


            loveList: [],
            registList: [],



            ifMyNum: false,//是否为我的次数


            fileList: [],//图片





        }
    },
    mounted() {

    },
    methods: {

        timeConfirm() {
            console.log(this.form.time);
            this.form.time = this.getNowDate(this.form.time)
            this.showTime = false
            console.log(this.getNowDate(this.form.time));
        },


        selectHandle(flag, obj) {
            if (flag == 1) {
                this.$router.push({
                    path: "/doctorDetail",
                    query: {
                        doctor: obj
                    },
                });
            } else {
                if (this.listFlag == 1) {

                    if (this.buyFlag) {
                        console.log(obj);

                        this.user.doctorId = obj.userId
                        this.user.helperId = obj.helperId
                        console.log(this.user);

                        this.submitHandle(2, 365)
                    } else {
                        this.form.doctorId = obj.userId
                        this.form.doctorName = obj.doctorName
                    }


                } else {

                    this.form.familyUserId = obj.userId
                    this.form.familyUserName = obj.userName
                }

                this.showlist = false
            }
        },


        showListHandle(flag) {


            console.log(this.doctorList);
            this.familyList = this.orderType == 1 ? this.loveList : this.registList
            this.listFlag = flag
            this.selectList = flag == 1 ? this.doctorList : this.familyList
            this.showlist = true
        },


        handle(flag, str) {

            console.log(str);

            // 提交申请
            if (str == 'add') {

                if (flag == 1 && this.num1 == 0) {
                    this.$toast('暂无可用次数')
                    return
                }

                if (flag == 0 && this.num0 == 0) {
                    this.$toast('暂无可用次数')
                    return
                }

                var arr = flag == 1 ? this.loveList : this.registList

                var a = arr.filter(item => {
                    return item.userId == this.userId
                })
                console.log(a);
                this.ifMyNum = a.length != 0
                if (flag == 1) {
                    console.log(this.doctorList);
                    this.doctorList.forEach(item => {
                        if (item.userId == this.user.doctorId) {
                            this.form.doctorId = item.userId
                            this.form.doctorName = item.doctorName
                        }
                    })
                }
                this.orderType = flag
                this.showPop = true
                // this.addOrderHandle(this.orderType)
            } else {
                this.$router.push({
                    path: '/historyList',
                    query: {
                        flag: flag,
                    },
                });
            }
        },

        numHandle(flag, type) {
            if (flag == 'pay') {
                this.num0 += 1
                this.num1 += 1
            } else {
                if (type == 1) {
                    this.num1 -= 1
                } else {
                    this.num0 -= 1
                }
            }


        },



        addOrderHandle(orderType) {

            console.log(this.form);
            // return
            if ((orderType == 1 && this.num1 == 0) || (orderType == 0 && this.num0 == 0)) {
                this.$toast('剩余次数不足')
                return
            }

            if (orderType == 0 && this.form.doctorId == '') {
                this.$toast('请选择就诊医生')
                return

            }

            if (!this.ifMyNum && this.form.familyUserId == '') {
                this.$toast('请选择审核人')
                return

            }
            if (orderType == 1 && this.fileList.length == 0) {
                this.$toast('请上传相关图片')
                return
            }

            let fd = new FormData();

            fd.append("userId", localStorage.userId);
            fd.append("doctorId", orderType == 1 ? this.user.doctorId : this.form.doctorId);
            fd.append("helperId", this.user.helperId);
            fd.append("orderType", orderType);
            fd.append("orderStatus", this.ifMyNum ? 3 : 0);
            fd.append("applyId", this.ifMyNum ? localStorage.userId : this.form.familyUserId);
            fd.append("parentId", this.user.parentId == 0 ? localStorage.userId : this.user.parentId);
            fd.append("payType", 0);
            fd.append("payStatus", 1);

            if (orderType == 1) {
                this.fileList.forEach(ele => {
                    fd.append("file", ele.file);
                });
            }
            userAddOrder(fd).then(res => {
                if (res.flag) {
                    this.$toast('提交成功')
                    console.log(res);
                    this.numHandle('use', orderType)
                    this.showPop = false
                    this.getNum()
                    this.fileList = []
                }
            })

            // userAddOrder({
            //     userId: localStorage.userId,
            //     // rechargeMoney: 365,
            //     doctorId: orderType == 1 ? this.user.doctorId : this.form.doctorId,
            //     helperId: this.user.helperId,
            //     orderType: orderType,
            //     orderStatus: this.ifMyNum ? 3 : 0,
            //     applyId: this.ifMyNum ? localStorage.userId : this.form.familyUserId,
            //     parentId: this.user.parentId,
            //     payType: 0,
            //     payStatus: 1
            // }).then(res => {
            //     if (res.flag) {
            //         this.$toast('提交成功')
            //         console.log(res);
            //         // this.numHandle('use', orderType)
            //         this.showPop = false
            //         this.getNum()
            //     }
            // })
        },


        submitHandle(flag, money) {

            if (this.user.doctorId == null || this.user.helperId == null) {
                this.$dialog.confirm({
                    title: '提示',
                    message: '您尚未绑定医生，请选择医生',
                    cancelButtonText: '再想想',
                    confirmButtonText: '选择医生'
                })
                    .then(() => {
                        this.buyFlag = true
                        this.selectList = this.doctorList
                        this.listFlag = 1
                        this.showlist = true

                    })
                    .catch(() => {
                        // on cancel
                        // this.tipShow = true
                    });
            }


            let fd = new FormData();
            console.log('-----------------------');
            console.log(Number(localStorage.userId));
            console.log(money);
            console.log(this.user.doctorId);
            console.log(this.user.helperId);
            console.log(flag);
            console.log(localStorage.userId);
            console.log(this.user.parentId == 0 ? localStorage.userId : this.user.parentId);

            fd.append("userId", Number(localStorage.userId));
            fd.append("rechargeMoney", money);
            fd.append("doctorId", this.user.doctorId);
            fd.append("helperId", this.user.helperId);
            fd.append("flag", flag);
            fd.append("applyId", Number(localStorage.userId));
            fd.append("parentId", this.user.parentId == 0 ? localStorage.userId : this.user.parentId);




            // this.$toast('优质服务，敬请期待！')
            addUserOrder({
                userId: localStorage.userId,
                rechargeMoney: money,
                doctorId: this.user.doctorId,
                helperId: this.user.helperId,
                flag,
                applyId: localStorage.userId,
                parentId: this.user.parentId == 0 ? localStorage.userId : this.user.parentId,
            }).then(res => {
                if (res.flag) {
                    if (flag == 2) {
                        console.log(res);
                        this.payHandle(res)
                    } else {
                        this.$toast('购买次数成功')
                        this.getNum()
                    }
                } else {
                    this.payError()
                }
            })

            return

            payTest(fd).then(res => {
                if (res.flag) {
                    console.log(res);
                    if (flag == 2) {
                        this.isVip = true
                        this.user.isVip = 1
                        localStorage.isVip = 1
                        this.$toast('开通/续费成功')
                    } else {
                        this.$toast('增加次数成功')
                    }
                    this.getNum()

                    this.buyFlag = false

                    this.$forceUpdate()

                    // this.payHandle(res.data.finalPackage)
                }
            })
        },

        //获取微信支付参数成功的回调函数
        payHandle: function (resObj) {
            console.log(resObj);
            // var result = JSON.parse(resObj);
            // console.log(result);
            var str = JSON.stringify(resObj.data.finalPackage);
            console.log(str);
            var that = this;
            //用返回参数 发起微信支付请求 
            plus.payment.request(wxChannel, str, function (data) {
                plus.ui.alert("支付成功!", function () {
                    that.isVip = true
                    that.user.isVip = 1
                    localStorage.isVip = 1
                    that.$toast('开通成功')
                    that.getNum()
                    that.$forceUpdate()
                })
            }, function (error) {
                console.log(JSON.stringify(error));
                that.$toast("支付失败");
            });
        },
        //获取微信支付参数失败的回调函数
        payError: function (e) {
            console.log(JSON.stringify(e));
            this.$toast("获取参数失败，请重试");
        },



        closeHandle() {
            this.showPop = false
            this.form = {
                doctorName: '', //选择的医生
                doctorId: '',
                time: '',
                familyUserId: '',//审核人id
                familyUserName: '',//审核人id
            }
        },

        backHandle() {
            this.$router.back()
        },

        getDoctorList() {

            listDoctors().then(res => {
                if (res.flag) {
                    res.data.forEach(item => {
                        item.id = item.doctorId
                        item.name = item.doctorName
                    })

                    this.doctorList = res.data.filter(item => {
                        return item.helperId != null
                    })
                    res.data.forEach(item => {
                        if (item.userId == this.myDoctorId) {
                            this.form.doctorId = item.userId
                            this.form.doctorName = item.doctorName
                        }
                    })

                }
            })
        },

        getNowDate(time) {
            var myDate = new Date(time);
            var year = myDate.getFullYear();
            var mon = myDate.getMonth() + 1;
            mon = mon < 10 ? '0' + mon : mon
            var date = myDate.getDate();
            date = date < 10 ? '0' + date : date
            var date1 = myDate.getDate() + 1;
            date1 = date1 < 10 ? '0' + date1 : date1
            var hours = myDate.getHours();
            hours = hours < 10 ? '0' + hours : hours
            var minutes = myDate.getMinutes();
            minutes = minutes < 10 ? '0' + minutes : minutes
            var seconds = myDate.getSeconds();
            seconds = seconds < 10 ? '0' + seconds : seconds
            return year + "-" + mon + "-" + date + ' ' + hours + ':' + minutes
        },

        getNum() {

            listFamilyNum({
                userId: localStorage.userId,
                parentCode: this.user.parentCode,
            }).then(res => {
                if (res.flag) {
                    this.isLoading = false

                    this.num0 = 0
                    this.num1 = 0
                    this.loveList = []
                    this.registList = []

                    if (res.data.length != 0) {
                        res.data.forEach(ele => {

                            if (ele.userId == localStorage.userId) {
                                this.user = ele
                                localStorage.user = JSON.stringify(ele)
                            }


                            ele.id = ele.userId
                            ele.name = ele.userName

                            this.num0 += ele.registNum
                            this.num1 += ele.loveNum
                            if (ele.loveNum != 0) {
                                this.loveList.push(ele)
                            }
                            if (ele.registNum != 0) {
                                this.registList.push(ele)
                            }
                        })

                    }

                    // red.data

                    console.log(res);
                }
            })


        },

        pullHandle() {

            this.isLoading = true
            this.getNum()
        },

        // 删除图片
        beforeDelete: function (e) {
            console.log(e);

            this.fileList = this.fileList.filter(item => {
                return item.file.name != e.file.name
            })

            console.log(this.fileList);
            console.log(this.file);

            // this.file = [];
            // this.fileList = [];
        },
        // 图片上传
        afterRead: function (file) {
            // 此时可以自行将文件上传至服务器
            this.file = file.file
            console.log(this.file);
        },


    },
    created() {
        this.getNum()
        this.getDoctorList()
    },
    //计算属性
    computed: {

    },
    filters: {

    }

}





</script>

<style lang='less' scoped>
.topBox {
    margin-bottom: 108px;
    box-sizing: border-box;
    padding-top: 68px;
    width: 750px;
    height: 260px;
    background: #FFFFFF;
    border-radius: 0 0 120px 120px;
    // overflow: hidden;
}

.topImg {
    box-sizing: border-box;
    padding: 50px 0 0 46px;
    display: flex;
    flex-direction: column;
    margin: 0px auto 0;
    width: 690px;
    height: 306px;
    background: linear-gradient(111deg, #14A870, #20BB66);
    border-radius: 20px;
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 36px;
    color: #FFFFFF;
    background-image: url(../../assets/img/familyImg.png);
    background-size: 100% 100%;
}

.topImg>span:first-child {
    margin-bottom: 14px;
}

.topImg>span:not(:first-child) {
    margin-bottom: 10px;
    font-size: 24px;
    color: rgba(255, 255, 255, .8);
}

.pageCon {
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: 100vh;
    background-color: #EEF1F7;
    overflow: hidden;
}


#reset /deep/ .van-nav-bar__left .van-nav-bar__text,
#reset /deep/ .van-nav-bar__left .van-icon {
    color: #333 !important;
}


.itemCon {
    box-sizing: border-box;
    padding: 28px 32px 40px 32px;
    margin: 0 auto 24px;
    width: 690px;
    background: #FFFFFF;
    box-shadow: 0px 2px 6px 0px rgba(51, 51, 51, 0.08);
    border-radius: 20px;
    font-family: Source Han Sans CN;
}


.itemTop {
    box-sizing: border-box;
    padding-left: 92px;
    margin-bottom: 16px;
    width: 100%;
    font-weight: bold;
    font-size: 28px;
    color: #333333;
}

.itemTop2 {
    padding-left: 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.itemTop2>div>span {
    font-size: 20px;
    color: #333;
    font-weight: 400;
    line-height: 36px;
}

.itemTop2>div:nth-child(2) {
    display: flex;
    align-items: baseline;
    color: #333;
    font-weight: 400;
    font-size: 20px;
    align-items: center;
}

.itemTop2>div:nth-child(2)>span {
    color: #1AB26B;
}

.itemTop2>div:nth-child(2)>span:nth-child(4),
.itemTop2>div:nth-child(2)>span:nth-child(2) {
    margin: 2px 12px 0;
    display: inline-block;
    width: 4px;
    height: 16px;
    background: #1AB26B;
    border-radius: 2px;
}

.itemMain {
    display: flex;
    width: 100%;
}

.itemMain>div:first-child {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 14px;
    margin-right: 30px;
    width: 62px;
    height: 62px;
    background: #F2F2F2;
    border-radius: 20px;
}

.itemMain>div:first-child>img {
    width: 38px;
    height: 38px;
}

.itemMain>div:nth-child(2) {
    flex: 1;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 20px;
    color: #858B90;
    line-height: 36px;
}

.btn {
    position: fixed;
    bottom: 158px;
    left: 92px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 564px;
    height: 72px;
    background: linear-gradient(146deg, #14A870, #20BB66);
    box-shadow: 0px 2px 6px 0px rgba(51, 51, 51, 0.08);
    border-radius: 36px;
    border: 1px solid #0E9249;
    font-family: Source Han Sans CN;
    font-weight: bold;
    font-size: 28px;
    color: #FFFFFF;
}

.btn>span {
    margin: 0 16px 0 20px;
    font-size: 20px;
    font-weight: 400;
}


.diaBox {
    width: 642px;
    // height: 362px;
    background: #FFFFFF;
    border-radius: 20px;
    font-family: Source Han Sans CN;

}

.diaBox>div:first-child {
    width: 100%;
    height: 110px;
    border-bottom: 2px solid #f2f2f2;
    text-align: center;
    font-weight: bold;
    font-size: 34px;
    color: #333333;
    line-height: 110px;
}

.infoBox {
    margin: 40px auto;
    box-sizing: border-box;
    padding: 18px 38px;
    width: 578px;
    // height: 280px;
    border-radius: 16px;
    border: 1px solid rgba(204, 204, 204, .5);

}

.infoLine {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    width: 100%;
    padding: 22px 0px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 28px;
    color: #334840;
    line-height: 64px;
}

.infoLine>span {
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 28px;
    color: #999999;
    line-height: 42px;
}

.infoLine:not(:last-child) {
    border-bottom: 2px solid #eee;
}

.diaBtnBox {

    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 90px;
    border-top: 2px solid #f2f2f2;
}

.diaBtnBox>div {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 100%;
    font-weight: bold;
    font-size: 28px;
    color: #333333;
    line-height: 64px;
}

.diaBtnBox>div:nth-child(2) {
    border-left: 2px solid #f2f2f2;
    color: #275141;
}

.doctorMain {
    width: 100%;
    height: 40vh;

}

.doctorMain>div {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    width: 100%;
    padding: 22px 44px;
    border-bottom: 2px solid #f2f2f2;
    font-size: 28px;
    color: #275141;
}

.doctorMain>div>div {
    font-size: 24px;
    color: #05a3ff;
}

.doctorMain>div>div>span {
    margin-left: 24px;
}

.infoLine1 {
    flex-direction: column;
    align-items: start;
}

::v-deep .van-uploader__upload,
::v-deep .van-image,
::v-deep .van-uploader__preview-image {
    margin-right: 20px;
    width: 120px;
    height: 120px;
}
</style>